import router from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Route } from "vue-router";
import { getModule } from "vuex-module-decorators";
import User from "@/store/modules/user";
import Store from "@/store";
import { RouterPath } from "@/utils/VEnum";

NProgress.configure({ showSpinner: false });

const whiteList = [
  RouterPath.LOGIN.toString(),
  RouterPath.INIT_ADMIN.toString()
];

const UserModule = getModule(User, Store);

router.beforeEach(async (to: Route, _: Route, next: any) => {
  NProgress.start();
  if (UserModule.token) {
    if (to.path === RouterPath.LOGIN) {
      next({ path: RouterPath.HOME });
      NProgress.done();
    } else {
      // if (!UserModule.user?.name) {
      //   try {
      //     await UserModule.getUserInfo();
      //     next({ ...to, replace: true });
      //   } catch (err) {
      //     UserModule.resetToken();
      //     next(RouterPath.Login);
      //     NProgress.done();
      //   }
      // } else {
      next();
      // }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(RouterPath.LOGIN);
      NProgress.done();
    }
  }
});

router.afterEach((to: Route) => {
  NProgress.done();
});
